package com.lb.shopguide.ui.fragment.guide;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.ImCache;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.ImBean;
import com.lb.shopguide.entity.UpdateInfoBean;
import com.lb.shopguide.entity.UserBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.im.Preference.Preferences;
import com.lb.shopguide.im.Preference.UserPreferences;
import com.lb.shopguide.ui.activity.GuideActivity;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.ClickUtil;
import com.lb.shopguide.util.lb.LogoutHelper;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by kang on 2017/4/18.
 */

public class FragmentEnterPhone extends BaseCommonFragment {
    @BindView(R.id.et_guide_phone)
    EditText etPhone;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;
    @BindView(R.id.tv_get_verifycode)
    TextView tvVerifyCode;
    @BindView(R.id.chk_protocol)
    CheckBox chkProtocol;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.ctb)
    ClearTitleBar ctb;

    private MyCountDown countDown;

    //    private String verifyNum;
    private ImBean imBean;
    private String phoneNum;
    //    private OnNextStepListener mOnNextStepListener;
//    private boolean isVerify = false;
    private UpdateInfoBean updateInfoBean;

    public static FragmentEnterPhone newInstance(UpdateInfoBean updateInfoBean) {
        FragmentEnterPhone fragment = new FragmentEnterPhone();
        Bundle bundle = new Bundle();
        if (updateInfoBean != null) {
            bundle.putSerializable(AppConstant.UPDATE_BEAN, updateInfoBean);
        }
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_enter_phone;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.UPDATE_BEAN)) {
            updateInfoBean = (UpdateInfoBean) bundle.getSerializable(AppConstant.UPDATE_BEAN);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
//        mOnNextStepListener = null;
    }


    @Override
    public void initView() {
        ctb.setLeftImageSrc(R.drawable.iv_boss_back);
        ctb.setLeftText("重新选择身份");
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ToastUtils.showShort("token过期");
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentEnterPhone.class.getName();
    }

    private void countDown() {
        if (countDown == null) {
            countDown = new MyCountDown(60000, 1000);
        }
        countDown.start();
    }

//    private void stopCountDown() {
//        if (countDown != null) {
//            countDown.cancel();
//        }
//        countDown = null;
//    }

    private boolean checkPhoneNum() {
        if (!chkProtocol.isChecked()) {
            ToastUtils.showShort("请先接受协议");
            return false;
        }
        phoneNum = etPhone.getText().toString();
        if (!TextUtils.isEmpty(phoneNum)) {
            if (RegexUtils.isMobileExact(phoneNum)) {
                return true;

            } else {
                ToastUtils.showShort("请输入正确的手机号码");
                return false;
            }
        } else {
            ToastUtils.showShort("手机号码不能为空");
            return false;
        }
    }

    @OnClick(R.id.tv_protocol)
    void protocolClick() {
        start(FragmentAgreement.newInstance("协议", "file:///android_asset/pro.htm", true));
    }

    @OnClick(R.id.tv_get_verifycode)
    void getVerifyCode() {
        if (checkPhoneNum()) {
            sendRequestGetVerifyNum(phoneNum);
        }
    }

    @OnClick({R.id.image_left, R.id.tv_left})
    void popClick() {
        pop();
    }

    @OnClick(R.id.btn_login)
    void btnLoginClick() {
        if (checkPhoneNum()) {
            if (!ClickUtil.isFastDoubleClick()) {
                String verifyNum = etVerifyCode.getText().toString();
                if (!TextUtils.isEmpty(verifyNum)) {
                    if (StringUtils.length(verifyNum) == 4) {
                        sendRequestVerifyPhone(phoneNum, verifyNum);
                    } else {
                        ToastUtils.showShort("请输入正确的验证码");
                    }
                } else {
                    ToastUtils.showShort("请输入验证码");
                }
            }
        }
    }


    private void savePreference(UserBean userBean, ImBean imBean, String token) {
        mUserConfigManager.setTerminalType(AppConstant.TERMINAL_TYPE_GUIDE);
        mUserConfigManager.setUserId(userBean.getStaffCode());
        mUserConfigManager.setStoreCode(userBean.getStoreCode());
        mUserConfigManager.setUserToken(token);
        mUserConfigManager.setStoreLogoUrl(userBean.getStoreLogoUrl());
        mUserConfigManager.setAccId(imBean.getAccid());
        mUserConfigManager.setImToken(imBean.getToken());
        mUserConfigManager.setUserName(userBean.getStaffNickName());
        mUserConfigManager.save2Sp(true);
        JPushInterface.setMobileNumber(mContext, AppConstant.SEQUENCE_SET_MOBILENUMBER, userBean.getMobileNum());
    }

    private void loginIm() {
        if (TextUtils.isEmpty(ImCache.getAccount())) {
            final String account = imBean.getAccid();
            final String token = imBean.getToken();
//            final String account = AppConstant.SERVICE_ACCID;
//            final String token = AppConstant.SERVICE_IM_TOKEN;
            // 登录
            AbortableFuture<LoginInfo> loginRequest = NimUIKit.login(new LoginInfo(account, token, AppConstant.YUNXIN_APPKEY), new RequestCallback<LoginInfo>() {
                @Override
                public void onSuccess(LoginInfo param) {
//                        onLoginDone();
                    ImCache.setAccount(account);
                    saveLoginInfo(account, token);
                    // 初始化消息提醒配置
                    initNotificationConfig();
                    Intent intent = ((GuideActivity) _mActivity).getGuideMainActivityIntent();
                    intent.putExtra(AppConstant.UPDATE_BEAN, updateInfoBean);
                    _mActivity.startActivity(intent);//顺序修改，修改问题，看看会不会有其他问题
                    _mActivity.finish();
                }

                @Override
                public void onFailed(int code) {
                    if (code == 302 || code == 404) {
//                        Toast.makeText(mContext, R.string.login_failed, Toast.LENGTH_SHORT).show();
                        sendRequestRefreshYXToken();
                    } else {
                        Toast.makeText(mContext, "im登录失败: " + code, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onException(Throwable exception) {
                    Toast.makeText(mContext, R.string.login_exception, Toast.LENGTH_LONG).show();
                }
            });
        } else {
            LogoutHelper.logout();
            loginIm();
        }
    }


    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = ImCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    private void sendRequestGetVerifyNum(String phone) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    KeyboardUtils.hideSoftInput(_mActivity);
                    if (!response.getMessage().equals("ok")) {
                        ToastUtils.showShort(response.getMessage());
                    }
                    countDown();
                }
            }
        };
        ApiMethodGuide.getVerifyNum(new SimpleLbObserver(listener, otherListener), phone, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestVerifyPhone(String phoneNum, String verifyNum) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    UserBean userBean = null;
                    try {
                        userBean = JsonUtil.getGson().fromJson(jsonObject.getString("staffInfo"), UserBean.class);
                        imBean = JsonUtil.getGson().fromJson(jsonObject.getString("imInfo"), ImBean.class);
                        String token = jsonObject.getString("token");
                        savePreference(userBean, imBean, token);
//                            loginPush(userBean);
                        loginIm();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodGuide.verifyPhone(new SimpleLbObserver(listener, otherListener), phoneNum, verifyNum, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestRefreshYXToken() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    String newToken = response.getReturnContent().toString();
                    imBean.setToken(newToken);
                    loginIm();
                }
            }
        };
        ApiMethodGuide.refreshGuideYXToken(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    class MyCountDown extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvVerifyCode.setClickable(false);
            tvVerifyCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tvVerifyCode.setClickable(true);
            tvVerifyCode.setText("重新发送");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (countDown != null) {
            countDown.cancel();
        }
    }
}
